package atech.ace.mapping;

import java.io.IOException;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import atech.ace.mapping.persistence.entities.HumanResource;

/**
 * Servlet implementation class CreateResource
 */
@WebServlet("/CreateResource")
public class CreateResource extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@PersistenceContext(name="jdbc/ACE_ProjectMapping")
	EntityManager em;
	
	@Resource
	UserTransaction utx;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HumanResource resource = new HumanResource();
		resource.setFirstName(request.getParameter("firstName"));
		resource.setLastName(request.getParameter("lastName"));
		resource.setEmail(request.getParameter("email"));
		resource.setExpertise(request.getParameter("expertise"));
		resource.setRegion(request.getParameter("region"));
		//resource.setJobTitle(request.getParameter("jobTitle"));
		
		String[] errs = Validation.validateResource(resource);
		if(errs.length > 0)
		{
			request.setAttribute("errs", errs);
			request.getRequestDispatcher("Create").forward(request, response);
		}
				
		
		try {
			utx.begin();
			em.persist(resource);
			utx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				utx.rollback();
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (SecurityException e1) {
				e1.printStackTrace();
			} catch (SystemException e1) {
				e1.printStackTrace();
			}
		} 
		

		response.sendRedirect("Create");
	}

}
